package com.sephiron.clocksynchronizer;

import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;


public class DatePickerFragment extends DialogFragment {
	public static final String EXTRA_DATE = "com.sephiron.clocksynchronizer.date";
	public static final String TAG = "DatePickerFragment";
	
	private Calendar mPickerDate;

	public static DatePickerFragment newInstance(Calendar date) {
		Bundle args = new Bundle();
		args.putSerializable(EXTRA_DATE, date);

		DatePickerFragment fragment = new DatePickerFragment();
		fragment.setArguments(args);

		return fragment;
	}

	private void sendResult(int resultCode) {
		if (getTargetFragment() == null) {
			return;
		}

		Intent i = new Intent();
		i.putExtra(EXTRA_DATE, mPickerDate);
		getTargetFragment().onActivityResult(getTargetRequestCode(),
				resultCode, i);
//		Toast.makeText(getActivity(), "sendResult() called", Toast.LENGTH_SHORT).show();
//		Log.d(TAG, "sendResult() called");
	}

	@Override
    @NonNull
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		mPickerDate = (Calendar) ((Calendar)getArguments().getSerializable(EXTRA_DATE)).clone();

		int year = mPickerDate.get(Calendar.YEAR);
		int month = mPickerDate.get(Calendar.MONTH);
		int day = mPickerDate.get(Calendar.DAY_OF_MONTH);

		View v = getActivity().getLayoutInflater().inflate(
				R.layout.dialog_date, null);


		// datePicker setting
		DatePicker datePicker = (DatePicker) v
				.findViewById(R.id.dialog_date_datePicker);
		datePicker.init(year, month, day, new OnDateChangedListener() {

			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mPickerDate.set(year, monthOfYear, dayOfMonth);
				getArguments().putSerializable(EXTRA_DATE, mPickerDate);
			}
		});

		return new AlertDialog.Builder(getActivity())
				.setView(v)
				.setTitle(R.string.date_picker_title)
				.setPositiveButton(
						android.R.string.ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								sendResult(Activity.RESULT_OK);
							}
						})
				.setNegativeButton(
						android.R.string.cancel, 
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
							}
						})
					
				.create();
	}

}